from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.decorators import action
from .models import BorrowRecord, Book,UserProfile
from .serializers import BorrowRecordSerializer
from utils.permissions import IsAdminOrReadOnly, IsOwnerOrAdmin
from .models import Announcement
from .serializers import AnnouncementSerializer
from .serializers import BookSerializer
from rest_framework import status, viewsets
from rest_framework.response import Response
from django.utils import timezone


class AnnouncementViewSet(viewsets.ModelViewSet):
    """
    公告视图集，支持增删改查操作。
    """
    queryset = Announcement.objects.all().order_by('-published_at')  # 按发布时间倒序排列
    serializer_class = AnnouncementSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]  # 可选：限制权限，仅登录用户可编辑




class BookViewSet(viewsets.ModelViewSet):
    """
    图书视图集，支持增删改查功能。
    """
    queryset = Book.objects.all().order_by('-id')  # 按 ID 倒序排列
    serializer_class = BookSerializer
    permission_classes = [IsAdminOrReadOnly]  # 使用自定义权限类

    def list(self, request, *args, **kwargs):
        """
        查询所有图书（读者和管理员都可以访问）
        """
        return super().list(request, *args, **kwargs)

    def create(self, request, *args, **kwargs):
        """
        创建新图书（仅图书管理员可以访问）
        """
        return super().create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        """
        更新图书信息（仅图书管理员可以访问）
        """
        return super().update(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """
        删除图书（仅图书管理员可以访问）
        """
        return super().destroy(request, *args, **kwargs)










class BorrowRecordViewSet(viewsets.ModelViewSet):
    """
    借阅记录视图集，支持借阅记录的查询和管理。
    """
    queryset = BorrowRecord.objects.all().order_by('-borrow_date')
    serializer_class = BorrowRecordSerializer
    permission_classes = [IsOwnerOrAdmin]  # 使用自定义权限类

    def get_queryset(self):
        """
        根据用户角色返回不同的借阅记录：
        - 普通用户：只能查看自己的借阅记录。
        - 管理员：可以查看所有用户的借阅记录。
        """
        user_profile = UserProfile.objects.get(user=self.request.user)
        if user_profile.role in ['admin', 'root']:  # 管理员和系统管理员
            return BorrowRecord.objects.all()
        return BorrowRecord.objects.filter(user=self.request.user)

    @action(detail=False, methods=['GET'], url_path='my-records')
    def my_records(self, request):
        """
        用户查看自己的借阅记录（包括当前借阅状态和历史记录）。
        """
        records = self.get_queryset()
        serializer = self.get_serializer(records, many=True)
        return Response(serializer.data)



class BookBorrowReturnViewSet(viewsets.ViewSet):
    """
    图书借还功能视图集，支持借书申请和归还确认。
    """

    def borrow_book(self, request, pk=None):
        """
        借书接口：用户申请借阅某本书。
        """
        try:
            book = Book.objects.get(pk=pk)
        except Book.DoesNotExist:
            return Response({"detail": "书籍不存在"}, status=status.HTTP_404_NOT_FOUND)

        user = request.user
        user_profile = UserProfile.objects.get(user=user)

        # 检查角色权限
        if user_profile.role not in ['user', 'admin']:
            return Response({"detail": "无权限借阅书籍"}, status=status.HTTP_403_FORBIDDEN)

        # 检查是否已借阅
        if BorrowRecord.objects.filter(user=user, book=book, return_date__isnull=True).exists():
            return Response({"detail": "你已经借阅了这本书"}, status=status.HTTP_400_BAD_REQUEST)

        # 创建借阅记录
        BorrowRecord.objects.create(user=user, book=book)
        return Response({"detail": f"成功借阅《{book.title}》"}, status=status.HTTP_201_CREATED)

    def return_book(self, request, pk=None):
        """
        还书接口：用户归还某本书。
        """
        try:
            book = Book.objects.get(pk=pk)
        except Book.DoesNotExist:
            return Response({"detail": "书籍不存在"}, status=status.HTTP_404_NOT_FOUND)

        user = request.user
        user_profile = UserProfile.objects.get(user=user)

        # 检查角色权限
        if user_profile.role not in ['user', 'admin']:
            return Response({"detail": "无权限归还书籍"}, status=status.HTTP_403_FORBIDDEN)

        try:
            record = BorrowRecord.objects.get(user=user, book=book, return_date__isnull=True)
        except BorrowRecord.DoesNotExist:
            return Response({"detail": "你未借阅这本书"}, status=status.HTTP_400_BAD_REQUEST)

        # 更新归还时间
        record.return_date = timezone.now()
        record.save()
        return Response({"detail": f"成功归还《{book.title}》"}, status=status.HTTP_200_OK)